package mi.payment.ui.base;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import mi.payment.R;
import mi.payment.constants.Params;
import mi.payment.db.dao.UserInfo;
import sunmi.sunmiui.title.Title;
import sunmi.sunmiui.utils.LogUtil;

/**
 * @author by longx on 2017/3/26.
 */

public abstract class BaseUpdatePWDActivity extends ParentActivity {

    private View oldPwdView;
    private View newPwdViewOne;
    private View newPwdViewTwo;
    private View commitView;

    private EditText editOldPwd;
    private EditText editNewPwdOne;
    private EditText editNewPwdTwo;

    private TextView tvCommit;
    private TextView tvNum;
    private TextView tvOldPwd;
    private ImageView imgLoading;

    private int oldPwdLength;
    private int newPwdLengthOne;
    private int newPwdLengthTwo;

    private Title mTitle;

    private int whoUpdate;

    private UserInfo userInfo;

    public abstract UserInfo getUserInfo();

    // 是谁来修改密码1为一般，2为大内总管，3为系统管理员，4为大内总管来添加小太监
    // 如果2来了根据uType判断是修改自己还是一般操作员
    public abstract int whoUpdate();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_password);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        whoUpdate = whoUpdate();
        userInfo = getUserInfo();
        LogUtil.e("lzc", "原密码" + userInfo.getUPwd());
        if (userInfo == null || whoUpdate == 868686) {
            showToast(getString(R.string.updatepwd_info_error));
            finish();
        } else {
            fillView();
        }
    }

    private void fillView() {
        switch (whoUpdate) {
            case 1:
                mTitle.setTitleText(getResources().getString(R.string.modify_general_password));
                tvNum.setText(getString(R.string.updatepwd_general) + userInfo.getUId());
                break;
            case 2:
                if (userInfo.getUType() == 1) {
                    mTitle.setTitleText(getResources().getString(R.string.modify_general_password));
                    tvNum.setText(getString(R.string.updatepwd_general) + userInfo.getUId());
                    oldPwdView.setVisibility(View.GONE);
                } else if (userInfo.getUType() == 2) {
                    mTitle.setTitleText(getResources().getString(R.string.modify_administrator_password));
                    tvNum.setText(getString(R.string.updatepwd_director) + "00");
                    setMaxLength(editOldPwd, 6);
                    setMaxLength(editNewPwdOne, 6);
                    setMaxLength(editNewPwdTwo, 6);
                    oldPwdView.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                mTitle.setTitleText(getResources().getString(R.string.modify_system_password));
                tvNum.setText(getString(R.string.updatepwd_system) + "99");
                break;
            case 4:
//                TextView menu = (TextView) findViewById(R.id.txt_head_title);
                mTitle.setTitleText(getResources().getString(R.string.updatepwd_add_operator));
                tvOldPwd.setText(getResources().getString(R.string.updatepwd_pwd));
                tvNum.setText(getString(R.string.updatepwd_general) + userInfo.getUId());
                newPwdViewOne.setVisibility(View.GONE);
                newPwdViewTwo.setVisibility(View.GONE);
                break;
        }
    }

    private void setMaxLength(EditText editText, int maxLength) {
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
    }

    private void initView() {
        tvOldPwd = (TextView) findViewById(R.id.txt_old_psd);
//        View back = findViewById(R.id.rel_back);
//        back.setOnClickListener(this);

        mTitle = (Title) this.findViewById(R.id.title);

        mTitle.setTitleText(getString(R.string.updatepwd_modify_pwd));
        mTitle.setHeadBgColor(getResources().getColor(R.color.colorBar));
        mTitle.setButtonVisibility(false, true, true, true);
        mTitle.setMenuClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }, null, null, null);

        oldPwdView = findViewById(R.id.rel_old_psd);
        newPwdViewOne = findViewById(R.id.rel_new_psd1);
        newPwdViewTwo = findViewById(R.id.rel_new_psd2);
        commitView = findViewById(R.id.rel_login);
        editOldPwd = (EditText) this.findViewById(R.id.editText2);
        editNewPwdOne = (EditText) this.findViewById(R.id.edit_new_psd1);
        editNewPwdTwo = (EditText) this.findViewById(R.id.edit_new_psd2);
        imgLoading = (ImageView) this.findViewById(R.id.img_round);
        tvCommit = (TextView) this.findViewById(R.id.text_comit);
        tvNum = (TextView) this.findViewById(R.id.txt_op_num);

        tvCommit.setOnClickListener(this);
        editOldPwd.addTextChangedListener(oldPwdWatcher);
        editNewPwdOne.addTextChangedListener(newPwdOneWatcher);
        editNewPwdTwo.addTextChangedListener(newPwdTwoWatcher);
        checkSubmitBtn();

        // 监听软键盘的完成按钮
        editNewPwdTwo.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    submit();
                    return true;
                }
                return false;
            }

        });
    }

    /**
     * 主管自己修改自己密码
     */
    private void systemUpdatePwd() {
        String old = editOldPwd.getText().toString();
        updatePassword(old);
    }

    private void submit() {
        // 1为一般，2为大内总管，3为系统管理员，4为大内总管来添加小太监
        switch (whoUpdate) {
            case 1:
                String old = editOldPwd.getText().toString();
                updatePassword(old);
                break;
            case 2:
                switch (userInfo.getUType()) {
                    case 1:
                        updatePassword(userInfo.getUPwd());
                        break;
                    case 2:
                        systemUpdatePwd();
                        break;
                }
                break;
            case 3:
                systemUpdatePwd();
                break;
            case 4:
                addAccount();
                break;
        }
    }


    private TextWatcher oldPwdWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            oldPwdLength = s.length();
            checkSubmitBtn();
        }

    };

    private TextWatcher newPwdOneWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            newPwdLengthOne = s.length();
            checkSubmitBtn();
        }

    };

    private TextWatcher newPwdTwoWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }


        @Override
        public void afterTextChanged(Editable s) {
            newPwdLengthTwo = s.length();
            checkSubmitBtn();
        }

    };

    private void addAccount() {

        final String newStr = editOldPwd.getText().toString();

        startAnimation();

        executeTask(new Runnable() {

            @Override
            public void run() {

                final int type = mUserInfoModel.addNewUser(newStr);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (type == 1) {
                            showToast(getResources().getString(R.string.updatepwd_add_success));
                            finish();
                        } else if (type == 2) {
                            showToast(getResources().getString(R.string.updatepwd_nogenerate_id));
                        } else if (type == 3) {
                            showToast(getResources().getString(R.string.updatepwd_usernum23));

                        }
                        tvCommit.setText(getResources().getString(R.string.updatepwd_submit));
                        hideAnimation();
                    }

                });

            }

        });

    }

    private void startAnimation() {
        imgLoading.setVisibility(View.VISIBLE);
        Animation operatingAnim = AnimationUtils.loadAnimation(this, sunmi.sunmiui.R.anim.loading_anim);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        imgLoading.setAnimation(operatingAnim);
        imgLoading.startAnimation(operatingAnim);
    }

    private void hideAnimation() {
        imgLoading.clearAnimation();
        imgLoading.setVisibility(View.GONE);
    }

    private void checkSubmitBtn() {
        switch (whoUpdate) {
            case 1:
                if (newPwdLengthTwo >= 4 && newPwdLengthOne >= 4 && oldPwdLength >= 4) {
                    commitView.setBackgroundResource(R.drawable.login_click_ripple);
                    commitView.setOnClickListener(this);
                } else {
                    commitView.setBackgroundResource(R.drawable.bg_gray_corner_login_btn);
                    commitView.setOnClickListener(null);
                }
                break;
            case 2:
                switch (userInfo.getUType()) {
                    case 1:
                        if (newPwdLengthTwo >= 4 && newPwdLengthOne >= 4) {
                            commitView.setBackgroundResource(R.drawable.login_click_ripple);
                            commitView.setOnClickListener(this);
                        } else {
                            commitView.setBackgroundResource(R.drawable.bg_gray_corner_login_btn);
                            commitView.setOnClickListener(null);
                        }
                        break;
                    case 2:
                        if (newPwdLengthTwo >= 4 && newPwdLengthOne >= 4 && oldPwdLength >= 4) {
                            commitView.setBackgroundResource(R.drawable.login_click_ripple);
                            commitView.setOnClickListener(this);
                        } else {
                            commitView.setBackgroundResource(R.drawable.bg_gray_corner_login_btn);
                            commitView.setOnClickListener(null);
                        }
                        break;
                }
                break;
            case 3:
                if (newPwdLengthTwo >= 4 && newPwdLengthOne >= 4 && oldPwdLength >= 4) {
                    commitView.setBackgroundResource(R.drawable.login_click_ripple);
                    commitView.setOnClickListener(this);
                } else {
                    commitView.setBackgroundResource(R.drawable.bg_gray_corner_login_btn);
                    commitView.setOnClickListener(null);
                }
                break;
            case 4:
                if (oldPwdLength >= 4) {
                    commitView.setBackgroundResource(R.drawable.login_click_ripple);
                    commitView.setOnClickListener(this);
                } else {
                    commitView.setBackgroundResource(R.drawable.bg_gray_corner_login_btn);
                    commitView.setOnClickListener(null);
                }
                break;
        }
    }

    /**
     * 主管修改一般操作员密码
     */
    private void updatePassword(String oldPsd) {
        final String newStrOne = editNewPwdOne.getText().toString();
        final String newStrTwo = editNewPwdTwo.getText().toString();
        if (TextUtils.isEmpty(oldPsd)) {
            showToast(getResources().getString(R.string.update_old_pwd_input));
            return;
        }
        if (TextUtils.isEmpty(newStrOne)) {
            showToast(getResources().getString(R.string.update_new_pwd_input));
            return;
        }
        if (TextUtils.isEmpty(newStrTwo)) {
            showToast(getResources().getString(R.string.update_new_pwd_input2));
            return;
        }
        if (!oldPsd.equals(userInfo.getUPwd())) {
            showToast(getResources().getString(R.string.updatepwd_oldpwd_error));
            return;
        }
        if (newStrOne.length() < 4 || newStrTwo.length() < 4) {
            showToast(getResources().getString(R.string.update_pwd_less_four));
            return;
        }

        if (newStrOne.length() >= 4 && newStrOne.equals(newStrTwo)) {
            if (!TextUtils.isEmpty(oldPsd) && oldPsd.equals(newStrOne)) {
                showToast(getResources().getString(R.string.updatepwd_pwd_noequal));
                return;
            }
            startAnimation();
            tvCommit.setText(getResources().getString(R.string.updatepwd_submiting));
            executeTask(new Runnable() {

                @Override
                public void run() {
                    final UserInfo info = mUserInfoModel.modifyUserPwd(userInfo.getUId(), userInfo.getUPwd(), newStrTwo);
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (info != null) {
                                showToast(getResources().getString(R.string.updatepwd_modify_success));
                                if(info.getUType()==1) {
                                    Params.userInfo = info;
                                }
                                LogUtil.e("lzc", "修改后的密码" + info.getUPwd());
                                finish();
                            } else {
                                showToast(getResources().getString(R.string.updatepwd_modify_error));
                                tvCommit.setText(getResources().getString(R.string.updatepwd_submit));
                            }
                            hideAnimation();
                        }

                    });

                }

            });

        } else {
            showToast(getResources().getString(R.string.updatepwd_twice_noequals));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.rel_back:
//                finish();
//                break;
            case R.id.rel_login:
                submit();
                break;
        }
    }

}
